import { DBHandler } from "../../database";
import type { selectConfig, codeSnippet } from "../../types";
import { deleteInvalid } from "../../utils";
import Koa from "koa";
import { DBConfig } from "../../database/DBConfig";

const findDoc: (findConfig?: selectConfig) => Promise<{
  codeData: codeSnippet[];
  userName: string | undefined;
}> = async (findConfig?: selectConfig) => {
  let data: codeSnippet[] = await DBHandler.find(
    DBConfig.collection,
    deleteInvalid(findConfig)
  );
  // console.log(data.length);
  return { userName: findConfig?.userName, codeData: data };
};

const updateDocCodeById: (
  oldId: string,
  newCode: string
) => Promise<boolean> = async (oldId: string, newCode: string) => {
  let updateFlag: boolean = await DBHandler.update(
    DBConfig.collection,
    { uuid: oldId },
    { code: newCode }
  );
  console.log("数据更新成功");
  return updateFlag;
};

const selectFromDB = async (
  ctx: Koa.ParameterizedContext<Koa.DefaultState, Koa.DefaultContext, any>
) => {
  let findConfig: selectConfig = {};
  findConfig.userName = ctx.request.query.userName as string;
  findConfig.code = ctx.request.query.code as string;
  findConfig.type = ctx.request.query.type as string;
  console.log(findConfig);
  ctx.response.body = await findDoc(findConfig);
};

const updateToDB = async (
  ctx: Koa.ParameterizedContext<Koa.DefaultState, Koa.DefaultContext, any>
) => {
  let newCode: string = ctx.request.query.code as string;
  let _id: string = ctx.request.query.id as string;
  ctx.response.body = await updateDocCodeById(_id, newCode);
};

export { selectFromDB, updateToDB };
